package com.ken.zeratul.commons.request;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletRequestUtils {

    /**
     * 获取请求对象
     * @return
     */
    public static HttpServletRequest getRequest() {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return requestAttributes.getRequest();
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 获取响应对象
     */
    public static HttpServletResponse getResponse() {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return requestAttributes.getResponse();
        } catch (Exception e) {
        }
        return null;
    }


    /**
     * 获取访问参数的方法
     * @param name
     * @return
     */
    public static String requestParam(String name) {
        try {
            HttpServletRequest request = getRequest();
            String parameter = request.getParameter(name);
            if (ObjectUtil.isNotEmpty(parameter)) {
                return parameter;
            }
            return request.getHeader(name);
        } catch (Exception e) {
        }
        return null;
    }
}
